var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    inputValue:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserInfo()
  },

  //获取用户个人信息
  getUserInfo: function () {
    var that = this;
    wx.request({
      url: app.host + '/user/info/',
      header: {
        accessToken: app.accessToken
      },
      method: 'GET',
      complete: function (res) {
        if (res.data.code == 0) {
          that.setData({
            userInfo: res.data.data
          })
        }
        wx.hideLoading()
      }
    })
  },

  //向服务器发送报名formId
  addFormId: function (e) {
    console.log(e)
    var formId = e.detail.formId
    var openId = app.userInfo.openId
    wx.request({
      url: app.host.url + '/wechat/template/common',
      data: {
        template: fromId,
        userId: uid,
        openId: openId
      },
      method: 'POST',
      complete: function (res) {
        console.log("请求新增微信formId")
        console.log(res)
      }
    })
  },

  formSubmit: function (e) {
    var formData = e.detail.value
    console.log(formData)
    // formData.id = this.data.userInfo.id
    var name = this.data.updateName
    if (name == 'email') {
      console.log('当前修改的是邮箱')
      var value = formData.email
      if(!this.checkEmail(value)){
        console.log('邮箱格式不对')
        wx.showToast({
          title: '邮箱格式不正确!',
          icon: 'none'
        })
        return
      }
    }
    if (name == 'phone') {
      var value = formData.phone
      if(!this.checkPhone(value)){
        wx.showToast({
          title: '手机号码格式不正确!',
          icon: 'none'
        })
        return
      }
    }
    this.setData({
      isShow: false,
      formData: formData,
      inputValue:""
    })
    this.updateUserInfo()
  },

  checkEmail: function (str) {
    var re = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
    if (re.test(str)) {
      return true
    } 
    return false
  },

  checkPhone: function (str) {
    var re = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (re.test(str)) {
      return true
    } 
    return false
  },

  updateUserInfo: function (res) {
    var that = this;
    var fromData = this.data.formData
    //判断手机号码格式是否正确
    //判断邮箱格式是否正确
    wx.request({
      url: app.host + '/user/update',
      header: {
        accessToken: app.accessToken
      },
      data: fromData,
      method: 'post',
      complete: function (res) {
        console.log(res)
        if (res.data.code == 0) {
          that.getUserInfo()
        }
        wx.hideLoading()
      }
    })
  },

  //控制分享弹窗
  showModal: function (e) {

    this.setData({
      isShow: true,
      updateTitle: e.currentTarget.dataset.title,
      updateName: e.currentTarget.dataset.name
    })
  },
  hideModal: function (e) {
    this.setData({
      isShow: false
    })
  },



})